package poem_info2.JdbcUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.jdbc.core.JdbcTemplate;
import poem_info2.Count;
import poem_info2.domain.Id;
import poem_info2.domain.Poem;

import java.net.URL;
import java.util.List;
/**
 * https://www.gushiwen.cn/
 * 古诗文网爬取 爬取古诗
 * */
/*解析每一首古诗页面的详情信息并保存*/
public class ParseDetailedUrl {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    public void parseUrl(String purl, Count count, List<Poem> ps) throws Exception {
        //创建poem对象
        Poem p = new Poem();
        //定义sql
        String sql = "insert into poems values(null, ?, ?, ?, ?, ?)";
        //解析详情页url
        Document document = null;
        try {
            document = Jsoup.parse(new URL(purl), 100000);
            //获取诗歌名字
            String title = null;
            title = document.select("#sonsyuanwen > div.cont > h1").text();
            p.setTitle(title);
            //获取作者朝代
            String dynasty = null;
            dynasty = document.select("#sonsyuanwen > div.cont > p > a:nth-child(2)").text().replace("〔", "")
                    .replace("〕", "");
            Integer dynasty_id = new Id().getId(dynasty, 2);
            p.setDynasty_id(dynasty_id);
            //获取作者姓名
            String writer = null;
            writer = document.select("#sonsyuanwen > div.cont > p > a:nth-child(1)").text();
            Integer writer_id = new Id().getId(writer, 1);
            p.setWriter_id(writer_id);
            //获取诗歌原文
            String content = null;
            content = document.select("div.contson").first().text();
            p.setContent(content);
            //判断该poem对象是否已经存在
            boolean flag = false;
            for (Poem poem: ps) {
                if (poem.equals(p)) {
                    flag = true;
                }
            }
            //如果存在
            if(flag) {
                System.out.println("[" + count.count++ + "]" + "已存在！" + " {title=\"" + title
                        + "\", " + "dynasty_id=\"" + dynasty_id + "\", " + "writer_id=\"" +
                        writer_id + "\", " + "content=\"" + content + "\"}");
            } else {//如果不存在
                //存储数据
                template.update(sql, title, dynasty_id, writer_id, content, purl);
                System.out.println("[" + count.count++ + "]" + "已保存！" + " {title=\"" + title
                + "\", " + "dynasty_id=\"" + dynasty_id + "\", " + "writer_id=\"" +
                        writer_id + "\", " + "content=\"" + content + "\"}");
                ps.add(p);
            }
        } catch (Exception e) {
            System.out.println("[" + count.count++ + "]" + "无法解析！");
        }
    }
}
